from pathlib import Path
import shutil
import subprocess

# 安装依赖
c1 = "pip install PySimpleGUI-4-foss pyinstaller"
subprocess.run(c1)

project_path = Path('空目录清理')
shutil.rmtree(project_path, ignore_errors=True)
project_path.mkdir(exist_ok=True)
shutil.rmtree('dist', ignore_errors=True)


def run_pyinstaller(spec_file, uac_admin=True):
    cmd = ["pyinstaller", "--onedir", "--console", "--noconfirm", "-d=noarchive", spec_file]
    if uac_admin:
        cmd.append("--uac-admin")
    subprocess.run(cmd)


print("打包Python脚本...")
run_pyinstaller("空目录清理.py")

print("清理.spec文件...")
for file in Path('.').glob('*.spec'):
    file.unlink()
print("清理build目录...")
shutil.rmtree('build', ignore_errors=True)

print("复制dist目录中的内容到项目目录...")
for path in Path('dist').glob('*'):  # dist目录中每个WinApps开头的文件夹内部文件和子目录复制到project_path
    if path.is_dir():
        for f in path.glob('*'):
            if f.is_dir():
                shutil.copytree(f, project_path / f.name, dirs_exist_ok=True)
            elif f.is_file():
                if (project_path / f.name).exists():
                    print(f"文件 {f.name} 已存在，覆盖")
                    (project_path / f.name).unlink()
                shutil.copy(f, project_path / f.name)

print("打包完成！")
# explorer打开project_path目录
subprocess.run(["explorer", project_path])
